package com.example.bgmachine.bgmachine;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.widget.Toast;


import com.example.bgmachine.bgmachine.waitviews.ProducewaitCirclePgBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;

public class UpdateManger {
    private Context mContext;
    //����汾����url
    private final static String VersionURL = "http://....";

    //private static final String SavePath = "/sdcard/drinkconrolls/";
    private String SavePath = "/sdcard/drinkconrolls/";
    private String VersionName = "1.0.0.1";

    //private static final String SaveFileName = SavePath + "UpdateDemoRelease.apk";
    private String SaveFileName = SavePath +"UpdateDemoRelease.apk"; // SavePath +

    public String ApkDownloadUrl = "http://39.100.244.66/testapp/testapp.apk";
    public int mlength = 1;
    public ProducewaitCirclePgBar producewait_circlepg_bar = null;

    public UpdateManger(Context context) {

        this.mContext = context;
        if (false) {
            try {

                File pathsFile = mContext.getDir("users", Context.MODE_PRIVATE);//Environment.getExternalStorageDirectory();//getDataDirectory();// mContext.getDir("users", Context.MODE_PRIVATE);

                File appDir = new File(pathsFile, "temp");
                if (!appDir.exists()) {
                    Log.d("aaa", "fileIsExists==1");
                    appDir.mkdir();
                } else {
                    Log.d("aaa", "fileIsExists==2");
                }
               SavePath = appDir.getPath();//appDir.getAbsolutePath();
                SaveFileName =   SavePath + File.separator + "UpdateDemoRelease.apk";//SavePath + "/UpdateDemoRelease.apk";
                File file = new File(SavePath);
                if (!file.exists()) {
                    //    Toast.makeText(mContext,"make=="+SaveFileName,Toast.LENGTH_SHORT).show();
                    file.mkdir();
                }
                File files = new File(SaveFileName);
                boolean resuals = files.delete();
                if(resuals){
                    Log.d("aaa", "createPaths:true");
                }else{
                    Log.d("aaa", "createPaths:false");
                }
            } catch (Exception e) {
                Log.i("aaa", "崩溃");

            }
           // Toast.makeText(mContext, SavePath+" == "+SaveFileName, Toast.LENGTH_SHORT).show();
        }

    }

    public Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Log.d("aaaaa", "ccccc: ");
            //   Toast.makeText(mContext, "myTopic myTopic="+myTopic , Toast.LENGTH_SHORT).show();
            switch (msg.what) {
                case 1:
                    String responsa = (String) msg.obj;
                    try {
                        // ����ľ��������ʽӦ�����Լ����������ص����ݶ���
                        JSONObject jsonObj = new JSONObject(responsa);
                        int code = jsonObj.getInt("code");
                        if (code == 0) {
                            JSONObject valueObj = jsonObj.getJSONObject("value");
                            String newVersion = valueObj.getString("version");
                            ApkDownloadUrl = valueObj.getString("url");
                            if (VersionName.equals(newVersion)) {

                            } else {

                            }
                        } else {

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case 2:
                    String responsb = (String) msg.obj;
                    Log.d("aaaaa", "responsb:==" + responsb);
                    installApk();
                    break;
                case 3:
                    int couta = (int) msg.obj;
                    Log.d("aaaaa", "DownLoadApk == couta =" + String.valueOf(couta));
                    if (producewait_circlepg_bar != null) {
                        producewait_circlepg_bar.setCurrentProgress(couta * 100 / mlength);
                    }

                    break;
            }
        }
    };

    private boolean updateVersion() {

        boolean isUpdate = getNewVersionName(VersionName);
        return isUpdate;
    }

    private boolean getNewVersionName(String version) {
        boolean isUpdate = false;
        String url = VersionURL + "?version=" + version;
        get(url);

        return isUpdate;
    }

    private void get(final String url) {

        new Thread(new Runnable() {

            @Override
            public void run() {
                String strUrl = url;
                URL url = null;
                try {
                    long currentTime = System.currentTimeMillis();
                    String timeNow = new SimpleDateFormat("yyyy-MM-dd").format(currentTime);
                    url = new URL(strUrl);
                    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
                    urlConn.setDoInput(true);
                    urlConn.setDoOutput(true);
                    urlConn.setRequestMethod("POST");
                    urlConn.setUseCaches(false);
                    urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    urlConn.setRequestProperty("Charset", "utf-8");

                    urlConn.connect();

                    DataOutputStream dop = new DataOutputStream(urlConn.getOutputStream());
                    dop.writeBytes("shopInformationId=" + "");
                    dop.writeBytes("&OrderInformationOrderTime=" + timeNow);
                    dop.flush();
                    dop.close();
                    BufferedReader bufferReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
                    String result = "";
                    String readline = null;
                    while ((readline = bufferReader.readLine()) != null) {
                        result += readline;
                    }
                    bufferReader.close();
                    urlConn.disconnect();

                    Log.d("aaaaa", "minqq=" + result);

                    String resulta = result;

                    Message msg = new Message();
                    String str1;
                    str1 = resulta;

                    msg.what = 1;
                    msg.obj = str1;
                    handler.sendMessage(msg);

                } catch (IOException e) {

                    Log.d("aaaaa", "222=");

                    e.printStackTrace();
                }

            }
        }).start();//这个start()方法不要忘记了

    }

    public void DownLoadApk() {  //����apk�����߳�
        Log.d("aaaaa", "DownLoadApk == 1");
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Log.d("aaaaa", "DownLoadApk == ApkDownloadUrl =" + ApkDownloadUrl);
                    URL url = new URL(ApkDownloadUrl);

                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

                    conn.setDoInput(true);
                    conn.setDoOutput(true);
                    conn.setRequestMethod("GET");
                    conn.setUseCaches(false);
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    conn.setRequestProperty("Charset", "utf-8");
                    /*
                    if (conn instanceof HttpsURLConnection) {
                        try {
                            SSLContext sslContext = HttpsUtil.getSSLContextWithCer();

                            if (sslContext != null) {
                                SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
                                ((HttpsURLConnection) conn).setDefaultSSLSocketFactory(sslSocketFactory);

                            }
                        } catch (Exception e) {
                            e.printStackTrace();

                        }

                    }

                     */
                  //  File downloadDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
                  //  SaveFileName =  downloadDir.getPath().toString()+ File.separator + "UpdateDemoRelease.apk";
                    conn.connect();
                    int length = conn.getContentLength();
                    InputStream is = conn.getInputStream();

                    File file = new File(SavePath);
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    File file1 = new File(SaveFileName);
                    if (file1.exists()) {
                        if (file1.delete()) {
                            // 文件删除成功
                            Log.d("FileDelete", "文件删除成功");
                        } else {
                            // 文件删除失败
                            Log.e("FileDelete", "文件删除失败");
                        }
                    }


                    String apkFile = SaveFileName;
                    Log.d("aaaaa", "DownLoadApk == apkFile =" + apkFile);
                    File ApkFile = new File(apkFile);
                    FileOutputStream fos = new FileOutputStream(ApkFile);

                    int count = 0;
                    byte buf[] = new byte[1024];
                    Log.d("aaaaa", "DownLoadApk == length =" + String.valueOf(length));
                    if (length <= 0) {
                        length = 1;
                    }
                    mlength = length;
                    do {
                        int numread = is.read(buf);
                        count += numread;
                        Log.d("aaaaa", "DownLoadApk == numread =" + String.valueOf(numread));
                        Log.d("aaaaa", "DownLoadApk == count =" + String.valueOf(count));
                        if (numread <= 0) {
                            fos.close();
                            is.close();
                            Message msg = new Message();
                            String str1;
                            str1 = "";
                            Log.d("aaaaa", "DownLoadApk == end =");
                            Log.d("aaaaa", "DownLoadApk == length =" + String.valueOf(length));
                            msg.what = 2;
                            msg.obj = str1;
                            handler.sendMessage(msg);
                            break;
                        } else {
                            Message msg = new Message();
                            msg.what = 3;
                            msg.obj = count;
                            handler.sendMessage(msg);
                        }
                        fos.write(buf, 0, numread);
                    } while (true);

                    fos.close();
                    is.close();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }

    //  @SuppressWarnings("unused")
    private void installApk() {
        Log.d("aaaaa", "installApk:==" + SaveFileName);
        //hasRootPerssion();
//        File apkfile = new File(SaveFileName);//File(mSavePath,Constant.appFileName);
//        if (!apkfile.exists()) {
//            return;
//        }
//        // 通过Intent安装APK文件
//        Intent i = new Intent(Intent.ACTION_VIEW);
//        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
//                "application/vnd.android.package-archive");
//        mContext.startActivity(i);
//        android.os.Process.killProcess(android.os.Process.myPid());
        if(false){
            File apkFile=  new File(SaveFileName);

            if (!apkFile.exists()) {

                return;
            }

            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            // 适配Android 7.0及以上版本
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                Uri contentUri = FileProvider.getUriForFile(
                        mContext,
                        mContext.getPackageName() + ".fileprovider",
                        apkFile
                );
                intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            } else {
                intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
            }

            mContext.startActivity(intent);
            return;
        }
        if(false){
            try {
                File apkFile = new File(SaveFileName);

                String authority = mContext.getPackageName() + ".fileprovider";
                Uri apkUri = FileProvider.getUriForFile(mContext, authority, apkFile);

                Intent install = new Intent(Intent.ACTION_VIEW)
                        .setDataAndType(apkUri, "application/vnd.android.package-archive")
                        .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                        // 必须添加的flag ↓
                        .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                // Android 12+ 包可见性处理
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.) {
//                    install.setPackage(context.getDefaultInstallPackage());
//                }
                Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
                ResolveInfo resolveInfo = mContext.getPackageManager().resolveActivity(intent, 0);


                if(resolveInfo != null ){
                    install.setPackage(resolveInfo.activityInfo.packageName);
                }else{
                    install.setPackage(null);
                }

                mContext.startActivity(install);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return;
        }


        if(true){
            File Apkfile = new File(SaveFileName);
            if (!Apkfile.exists()) {
                return;
            }
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.parse("file://" + Apkfile.toString()), "application/vnd.android.package-archive");
            mContext.startActivity(intent);
        }else{
         //   SilentInstallUtils.silenceInstall(mContext,SaveFileName);
        }



//        Intent intent = new Intent();
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        intent.setAction(android.content.Intent.ACTION_VIEW);
//        intent.setDataAndType(Uri.fromFile(apkfile),
//                "application/vnd.android.package-archive");

//        mContext.startActivity(intent);
        /*
        PrintWriter PrintWriter = null;
        Process process = null;
        try {

            process = Runtime.getRuntime().exec("su");
            PrintWriter = new PrintWriter(process.getOutputStream());
            PrintWriter.println("chmod 777 " + SaveFileName);
            PrintWriter.println("export LD_LIBRARY_PATH=/vendor/lib:/system/lib");
            PrintWriter.println("pm install -r " + SaveFileName);
            PrintWriter.flush();
            PrintWriter.close();
            int value = process.waitFor();
            returnResult(value);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (process != null) {
                process.destroy();
            }
        }
*/

    }

    /**
     * 判断手机是否有root权限
     */
    public static boolean hasRootPerssion() {
        PrintWriter PrintWriter = null;
        Process process = null;
        try {
            process = Runtime.getRuntime().exec("su");
            PrintWriter = new PrintWriter(process.getOutputStream());
            PrintWriter.flush();
            PrintWriter.close();
            int value = process.waitFor();
            returnResult(value);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (process != null) {
                process.destroy();
            }
        }
        return false;
    }

    private static boolean returnResult(int value) {
        // 代表成功
        if (value == 0) {
            return true;
        } else if (value == 1) { // 失败
            return false;
        } else { // 未知情况
            return false;
        }
    }


}
